package org.iweb.html.api;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Observer implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = 5514845755973474820L;

	protected final static Logger log=LoggerFactory.getLogger(Observer.class);

	//private static Observer instance;

	//protected Observer(){}

	// listener id -> Listeners
	private Map<String, List<Listener>> listeners;

	public void setListeners(Map<String, List<Listener>> listeners) {
		this.listeners = listeners;
	}

	public Map<String, List<Listener>> getListeners() {
		if(listeners==null)
			listeners=new HashMap<String, List<Listener>>();
		return listeners;
	}

	public void registerListener(String id,Listener listener){


//		if(getListener(listener.getId())!=null)
//			log.warn("Un listener è già registrato con questo id, verrà sovrascritto");

		//getListeners().put(listener.getId(), listener);

		List<Listener> l=getListeners().get(id);
		if(l==null){
			l=new LinkedList<Listener>();
			getListeners().put(id, l);
		}

		l.add(listener);

		log.info("Listener registrati: "+getListeners().size());

		//getListeners().put(listener.getId, listener);
	}

	public List<Listener> getListener(String id){
		return getListeners().get(id);
	}

	public void unregisterListener(Listener listener){
		getListeners().remove(listener.getId());
	}

	/*
	public static Observer getInstance() {
		if(instance==null)
			instance=new Observer();
		return instance;
	}
	*/


	public void clean(){
		getListeners().clear();
	}


}
